﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using MobileAPI.Web.Data;
using MobileAPI.Common;


namespace MobileAPI.Web
{
    public partial class MobileApi : System.Web.UI.Page
    {
        public const int MaxRequestContentLength = 4 * 1024;

        protected void Page_Load(object sender, EventArgs e)
        {
            ProcessRequest();
        }

        /// <summary>
        /// 处理用户请求并返回相应结果
        /// </summary>
        private void ProcessRequest()
        {
            if (this.Request.ContentLength > MaxRequestContentLength)
            {
                this.Response.Write("提交的数据内容过大，系统未作处理");
                this.Response.End();
                return;
            }

            MobileRspMsg rspMsg = new MobileRspMsg();
            try
            {
                try
                {
                    /***************************************/
                    /* 若有通过 URL 地址传参的方式，可在此处处理
                    /***************************************/
                    //if(this.Request.QueryString["img"]!=null&&!String.IsNullOrEmpty(this.Request.QueryString["img"]))
                    //{
                    //    byte[] imgByte = DalCommodity.GetSmallCommodityImgByCommodityId(Request.QueryString["img"]);
                    //    Response.BinaryWrite(imgByte);
                    //    return;
                    //}   

                    // 读取移动端 POST 的数据
                    string msg = string.Empty;
                    using (StreamReader sr = new StreamReader(this.Request.InputStream, Encoding.UTF8, false, this.Request.ContentLength))
                    {
                        msg = sr.ReadToEnd();
                    }

                    // 保存请求信息
                    WriteLogToDisk(msg);

                    // 验证移动端发送的数据，并将其转化为 MobileReqMsg 对象
                    MobileReqMsg req = MobileReqMsg.VerifyData(msg);
                    if (req.Head.RspCode == MessageCode.Success.Code)
                    {
                        // 根据消息调用对应的 API
                        rspMsg = MobileAPIManager.CallAPI(req);
                    }
                    else
                    {
                        rspMsg.Head.RspCode = req.Head.RspCode;
                        rspMsg.Head.RspMsg = req.Head.RspMsg;
                    }
                }
                catch (Exception ex)
                {
                    rspMsg = new MobileRspMsg();
                    rspMsg.Head.RspCode = MessageCode.Server_Error.Code;
                    rspMsg.Head.RspMsg = MessageCode.Server_Error.Msg;
                    ErrorLogWriter.Write(ex);
                }

                // 保存返回信息
                WriteLogToDisk(rspMsg.ToXml());

                // 返回相应结果
                byte[] bytes = null;
                if (rspMsg.Head.UseGZip && rspMsg.Head.RspCode == MessageCode.Success.Code)
                {
                    bytes = rspMsg.Compress();
                }
                else
                {
                    bytes = rspMsg.ToBytes();
                }
                this.Response.OutputStream.Write(bytes, 0, bytes.Length);
                this.Response.OutputStream.Flush();
                this.Response.OutputStream.Close();
            }
            catch (Exception ex)
            {
                ErrorLogWriter.Write(ex);
            }
            finally
            {
                this.Response.End();
            }
        }

        /// <summary>
        /// 保存消息日志
        /// </summary>
        /// <param name="msg"></param>
        private void WriteLogToDisk(string msg)
        {
            bool logEnabled = bool.Parse(WebConfigurationManager.AppSettings["MobileAPI.Web.MsgLogEnabled"]);
            if (logEnabled)
            {
                MobileMsgLogWriter.Write(msg);
            }
        }
    }
}